﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

using Admin.NET.Application.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;
using System.Text.RegularExpressions;

namespace Radius.NET.Interface.Kingdee.Service.SaModule;

/// <summary>
/// 销售订单服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 005)]
public class SaOrderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SaOrders> saOrderRespository;
    private readonly KingdeeUtil _kingdeeUtil;

    public SaOrderService(SqlSugarRepository<SaOrders> _saOrderRespository,
        KingdeeUtil kingdeeUtil
        )
    {
        saOrderRespository = _saOrderRespository;
        _kingdeeUtil = kingdeeUtil;
    }

    #region 同步销售订单到本地
    /// <summary>
    /// 同步销售订单到本地
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="Bdate"></param>
    /// <param name="fbillNo"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/samodule/xsdd/list/{cid}"), AllowAnonymous]
    public async Task<object> SyncFhtzdList(int cid, string Bdate, string fbillNo)
    {
        var KingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_samodule_xsdd_list");
        if (string.IsNullOrEmpty(Bdate))
            Bdate = DateTime.Now.ToString();

        List<SaOrders> saorder_List = new();
        string filterString = $"FSaleOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FDate >= '{Bdate}' and FDocumentStatus='C'";
        if (!string.IsNullOrEmpty(fbillNo))
        {
            filterString += $" and FBillNo = '{fbillNo}'";
        }
        var list = KingdeeUtil.Query<SAL_SaleOrder_Dto>(KingdeeFormConst.SAL_SaleOrder, filterString );

        double index = 1;
        foreach (var item in list)
        {
            string orderId = item.FBillNo;
            if (!await saOrderRespository.IsAnyAsync(x => x.OrderID == orderId && x._cid == cid))
            {
                string FMaterialModel = item.FMaterialModel;
                double utwt = FMaterialModel is null || string.IsNullOrEmpty(FMaterialModel.Trim()) ? 1 : Convert.ToDouble(Regex.Replace(FMaterialModel, @"[^0-9]+", ""));
                var childObj = new SaOrdersDetail()
                {
                    OrderID = orderId,
                    Inventory_ID = item.FMaterialIdFNumber,
                    JARMODELID = "1",// item.ItemIndexOf(SAL_SaleOrder_FieldKeys, "FAuxpropID.FF100002.FNumber").ParseToString(),
                    BoxCode = "1",//item.ItemIndexOf(SAL_SaleOrder_FieldKeys, "FAuxpropID.FF100004.FNumber").ParseToString(),
                    Unit_Weight = utwt,
                    NBox = 1,
                    Qty = item.FQty,
                    NPKG = item.FQty,
                    Weight = item.FQty,
                    Standard_price = item.FPrice,
                    Amount = item.FAmount,
                    SalesType = 0,
                    PriceType= "产品均价(KG)",
                    No = index,
                    _cid = cid
                };

                if (saorder_List.FirstOrDefault(x => x.OrderID == orderId) is not null)
                {
                    saorder_List.FirstOrDefault(x => x.OrderID == orderId)?.FG_SaDetail.Add(childObj);
                }
                else
                {
                    saorder_List.Add(new SaOrders
                    {

                        #region 拼接主表字段
                        OrderID = orderId,
                        ContactNum = item.FCustIdFNumber,
                        OrderDate = item.FDate,
                        ShipDate = item.FDate,
                        Person_Incharge = item.FSalerIdFNumber,
                        Summary = item.FNote,
                        Maker = item.FCreatorIdFName,
                        _cid = cid,
                        #endregion

                        #region 拼接子表字段
                        FG_SaDetail = new List<SaOrdersDetail>() { childObj }
                        #endregion

                    });
                }
                index++;
            }
        }
        if (saorder_List.Count == 0)
            throw Oops.Bah("无可同步的数据或者已存在！");
        //插入BS数据库
        return await saOrderRespository.AsInsertable(saorder_List)
            //按导航属性插入子表
            .AddSubList(x => x.FG_SaDetail).ExecuteCommandAsync();
    }
    #endregion
}
